package com.cbtg.client;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;

import com.cbtg.client.https.HttpUtils;
import com.cbtg.client.utils.WtcJsonMap;

/**
 * 参数相关
 * 
 * @author macpl
 *
 */
public class CbtgClient {
	private String secret;
	private String operatorLoginname;
	private String operatorPassword;
	private String baseUrl;

	public CbtgClient(String baseUrl, String secret, String operatorLoginname, String operatorPassword) {
		super();
		this.secret = secret;
		this.baseUrl = baseUrl;
		this.operatorLoginname = operatorLoginname;
		this.operatorPassword = operatorPassword;
	}

	/**
	 * 服务是否可用
	 * 
	 * @return
	 */
	public boolean isLive() {
		Map<String, String> data = new HashMap<String, String>();
		data.put("secret", secret);
		data.put("operatorLoginname", operatorLoginname);
		data.put("operatorPassword", operatorPassword);
		// -----------
		data.put("loginname", operatorLoginname);
		JSONObject backData = HttpUtils.httpPost(baseUrl + "/api/get/user.do", data);
		if (!backData.has("STATE") || backData.getInt("STATE") != 0) {
			throw new RuntimeException(backData.toString());
		}
		return true;
	}

	/**
	 * 查询系统参数
	 * 
	 * @param paras
	 * 
	 * @param keyPart 部分key，模糊匹配
	 */
	public String getParameter(String key, String paras) {
		Map<String, String> data = new HashMap<String, String>();
		data.put("secret", secret);
		data.put("operatorLoginname", operatorLoginname);
		data.put("operatorPassword", operatorPassword);
		// -----------
		data.put("key", key);
		if (StringUtils.isNotBlank(paras)) {
			data.put("paras", paras);
		}
		JSONObject backData = HttpUtils.httpPost(baseUrl + "/api/get/parameter.do", data);
		if (!backData.has("STATE") || backData.getInt("STATE") != 0) {
			throw new RuntimeException(backData.toString());
		}
		WtcJsonMap json = new WtcJsonMap(backData.toMap());
		return json.getString("DATA");
	}

}
